package cn.hicard.risk.interf.merchInfo;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

import cn.hicard.risk.common.Constant;
import cn.hicard.core.Where;
import cn.hicard.risk.entity.BdBusiness;
import cn.hicard.risk.entity.BdMerchinfo;
import cn.hicard.risk.interf.vo.AppHead;
import cn.hicard.risk.interf.vo.RetBean;
import cn.hicard.risk.service.bd.BusinessService;
import cn.hicard.risk.service.bd.MerchInfoService;
import cn.hicard.util.DateHelp;
import cn.hicard.util.SpringContext;



public class MerchInterf {

	private static Logger logger = Logger.getLogger(Constant.LOGGER_MAIN);
	
	/**
	 * 服务端获取报文(商户资料信息)
	 * @param sDataStr
	 * @param interfaceCode
	 * @return
	 */
	public String getMerchInfo(String sDataStr) {
		String sJson = "";
		RetBean retBean=new RetBean();		
		ObjectMapper objectMapper = new ObjectMapper();
		BdMerchinfo merchinfo=new BdMerchinfo();
		BdBusiness bdBusiness=new BdBusiness();
		if (sDataStr==null||sDataStr.equals("")) {
			retBean.setRetCode("0000_01");	
			retBean.setRetMessage("获取到的json数据为空");	
		}else{
			try {
				Map<String, Object> maps = objectMapper.readValue(sDataStr.toString(), Map.class);
				logger.info(maps);
				
				Map<String, Object> AppBody=(Map<String, Object>) maps.get("AppBody");
				
				//商户信息新增or修改
				boolean merch=merchArrange(merchinfo,AppBody);
				//业务信息新增or修改
				boolean business=businessArrange(bdBusiness,AppBody);
				retBean.setAppHead(appHeadArrange(maps));
				if(merch==false){
					retBean.setRetCode(retBean.getAppHead().getTransType()+"_01");	
					retBean.setRetMessage("商户信息入库出错");
				}else if(business==false){
					retBean.setRetCode(retBean.getAppHead().getTransType()+"_01");	
					retBean.setRetMessage("业务信息入库出错");
				}else{					
					retBean.setRetCode(retBean.getAppHead().getTransType()+"_00");	
					retBean.setRetMessage("商户资料更新成功");
				}
			}catch(Exception e){
				retBean.setRetCode("0000_01");
				retBean.setRetMessage("商户资料json转换出错");
				logger.error("商户资料接收数据出错"+e);
				e.printStackTrace();
			}
		}
		try {
			ObjectMapper mapper2 = new ObjectMapper(); 
			StringWriter sw = new StringWriter();
			JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
			mapper2.writeValue(gen, retBean); 
			gen.close();
			sJson = sw.toString();		
			logger.info(sJson);
		} catch (Exception ex) {
			logger.error("商户资料返回json出错"+ex);
			ex.printStackTrace();		
		}
		
		return sJson;
	}
	
	/*
	 * 商户资料接口用
	 * appHeadMap转换成appHead实体类
	 * @return
	 */
	public AppHead appHeadArrange(Map<String, Object> map){
		AppHead appHead=new AppHead();
		Map<String, String> appHeadMap=(Map<String, String>) map.get("AppHead");
		appHead.setTransType(appHeadMap.get("TransType"));
		appHead.setSerialNo(appHeadMap.get("SerialNo"));
		appHead.setDataTime(appHeadMap.get("DataTime"));
		return appHead;
	}	
	

	
	/**
	 * 商户信息新增or修改
	 * @return
	 */
	public boolean merchArrange(BdMerchinfo merchinfo,Map<String, Object> AppBody){
		boolean b=true;
		MerchInfoService merchInfoService = (MerchInfoService)SpringContext.getBean("merchInfoService");
		try{
			Map<String, Object> industryFirstMap=(Map<String, Object>) AppBody.get("industryFirst");	//提取行业类别
			List<Map<String, Object>> posList= (List<Map<String, Object>>) AppBody.get("pos");			//提取打印商户号	
			Map<String, Object> provinceMap= (Map<String, Object>) AppBody.get("province");				//提取省份
			Map<String, Object>cityMap= (Map<String, Object>) AppBody.get("city");						//提取城市
			Map<String, Object>partnerMap= (Map<String, Object>) AppBody.get("partner");				//提取合作人
			//AppBody对象提取
			merchinfo.setHmId(getString(AppBody,"merNo"));    					//汇卡商户号
			merchinfo.setHmName(getString(AppBody,"merName"));  				//汇卡商户名
			merchinfo.setMerchDegree(getString(AppBody,"merGrade")); 			//商户等级1：普通商户2：vip商户3：超级vip4：灰名单 5：黑名单
			merchinfo.setType(getString(AppBody,"merType"));   	        		//商户类型	
			merchinfo.setStatus(getString(AppBody,"merStatus"));    			//状态
			merchinfo.setRiskDegree(getString(AppBody,"merRiskgrade"));   		//商户风控等级
			merchinfo.setAddress(getString(AppBody,"merBusaddress"));   	    //营业地址
			merchinfo.setCellphone(getString(AppBody,"merConmphone"));       	//移动电话
			merchinfo.setTelphone(getString(AppBody,"merContelephone"));        //固定电话
			merchinfo.setPrintName(getString(AppBody,"merNameput"));            //商户打印名称
			merchinfo.setLoginid(getString(AppBody,"merModifyman"));            //操作员
			merchinfo.setDayliquidation(getString(AppBody,"merDayquotab"));     //日银行卡限额
			merchinfo.setMonthliquidation(getString(AppBody,"merMonthquotab")); //月银行卡限额
			merchinfo.setDayclearinglimits(getString(AppBody,"merDayquotac"));  //日信用卡限额
			merchinfo.setMonthclearinglimits(getString(AppBody,"merMonthquotac"));//月信用卡限额
			merchinfo.setGetTicket(getString(AppBody,"merIsDiaodan"));			//是否调单
			merchinfo.setContactName(getString(AppBody,"merContacts"));			//联系人姓名
			merchinfo.setHmNameShort(getString(AppBody,"merNameshort"));		//商户简称
			merchinfo.setExpandPeople(getString(AppBody,"merExpandpeo"));		//扩展人
			//其他信息提取
			merchinfo.setIndustry(getString(industryFirstMap,"induf_name"));	//行业类别
			merchinfo.setUpdateTime(DateHelp.dateTime());			        	//同步时间
			if(posList.size()>0){
				merchinfo.setPrintNo(getString(posList.get(0),"posPrintMerchno"));//打印商户号
			}
			
			merchinfo.setTheProvince(getString(provinceMap,"province_name"));	//省份
			merchinfo.setTheCity(getString(cityMap,"city_name"));				//城市
			merchinfo.setPartner(getString(partnerMap,"partner_name"));			//合作人
		
			Where where =new Where(BdMerchinfo.class);
			where.addEqual("hmId", merchinfo.getHmId());
			List<BdMerchinfo>list=merchInfoService.findList(where);
			if(list.size()>0){
				merchinfo.setPkHmerch(list.get(0).getPkHmerch());
				//修改
				merchInfoService.update(merchinfo);
			}else{
				//新增
				merchInfoService.save(merchinfo);
			}
		}catch(Exception e){
			logger.error("商户信息整理出错"+e);
			e.printStackTrace();
			b=false;
		}		
		return b;
	}
	
	/**
	 * 业务信息新增or修改
	 * @return
	 */
	public boolean businessArrange(BdBusiness bdBusiness,Map<String, Object> AppBody){
		boolean b=true;
		BusinessService businessService= (BusinessService)SpringContext.getBean("businessService");
		try{
			Map<String, Object> industryFirstMap=(Map<String, Object>) AppBody.get("industryFirst");	//提取行业类别
			List<Map<String, Object>> posList= (List<Map<String, Object>>) AppBody.get("pos");			//pos终信息List
			List<Map<String, Object>> liquidateList= (List<Map<String, Object>>) AppBody.get("liquidates");			//清算信息list
				
			for(int i=0;i<posList.size();i++){
				for(int k=0;k<liquidateList.size();k++){
					if(posList.get(i).get("id").toString().equals(liquidateList.get(k).get("ldPosid").toString()))
					{
						
						//业务选项信息list集合(一台pos对应多种业务信息)
						List<Map<String, Object>> posBusiRatesList =(List<Map<String, Object>>)liquidateList.get(k).get("posBusiRates");
					
						for(int j=0;j<posBusiRatesList.size();j++){
							//单一业务选项信息
							Map<String, Object>	busiRateMap=(Map<String, Object>) posBusiRatesList.get(j).get("busiRate");
							//提取业务类型
							Map<String, Object>busiConfig=(Map<String, Object>)busiRateMap.get("config");
							//费率信息
							Map<String, Object>rateMap=(Map<String, Object>) busiRateMap.get("rate");
							//账号信息
							Map<String, Object>bankInfoMap=(Map<String, Object>) posBusiRatesList.get(j).get("bankInfo");
							//维护公司信息(提取维护方)
							Map<String, Object>	branchCompanyMap=(Map<String, Object>) posList.get(i).get("branchCompany");
								
							//AppBody对象提取
							bdBusiness.setHmId(getString(AppBody,"merNo"));  								//汇卡商户号			
							bdBusiness.setReachLimit(getLong(AppBody,"merStandardAmount"));					//达标额度
							bdBusiness.setChannelNo(getString(AppBody,"posChannelName"));					//渠道
							bdBusiness.setOrgId(getString(AppBody,"posInstitution"));						//收单机构
							bdBusiness.setPayChannel(getString(AppBody,"posChannelName"));					//出账渠道
							//liquidate对象提取
							bdBusiness.setStatus(getString(liquidateList.get(k),"ldState"));				//状态
							//pos对象提取
							bdBusiness.setHtId(getString(posList.get(i),"posHcunitcode"));					//汇卡终端号
							bdBusiness.setOmId(getString(posList.get(i),"posMerchno"));						//收单商户号
							bdBusiness.setOtId(getString(posList.get(i),"posPortno"));						//收单终端号
							bdBusiness.setPosStatus(getString(posList.get(i),"posState"));					//终端状态
							bdBusiness.setControlStatus(getString(posList.get(i),"posCtrlLogo"));			//终端控制标识
							bdBusiness.setRemark(getString(posList.get(i),"posNote"));						//备注
							bdBusiness.setReckCycle(getString(posList.get(i),"period")); 					//清算周期
							bdBusiness.setPosModel(getString(posList.get(i),"posModel")); 					//机型
							bdBusiness.setPosVersion(getString(posList.get(i),"posOrderno"));				//POS程序版本号
							bdBusiness.setAccessWay(getString(posList.get(i),"posConnmode"));				//接入方式
							bdBusiness.setOperations(getString(posList.get(i),"posOperators"));				//运营方
							bdBusiness.setIcReform(getString(posList.get(i),"posIsIcReform"));				//是否IC卡非接改造			
							//busiRateMap对象提取
							bdBusiness.setClient(getString(busiRateMap,"bu_client"));						//客户端
							bdBusiness.setTransMode(getString(busiRateMap,"bu_dealtype"));					//终端类型	
							bdBusiness.setCardType(getString(busiRateMap,"bu_cardtype"));					//卡类型
							bdBusiness.setCardMedia(getString(busiRateMap,"bu_cardmedium"));				//卡介质		
							bdBusiness.setCycle(getInt(busiRateMap,"bu_cycle"));							//出账周期 
							//posBusiRatesList对象提取
							bdBusiness.setBusinessType(getString(busiConfig,"busi_reckNo"));				//业务类型
							bdBusiness.setFeeEnableDate(getString(posBusiRatesList.get(j),"pbrRateStarttime"));//费率启用日期
							bdBusiness.setFeeFailDate(getString(posBusiRatesList.get(j),"pbrRateEndtime"));	  //费率失效日期
							bdBusiness.setMerchSystemId(getInt(posBusiRatesList.get(j),"id"));				//商户系统ID
							bdBusiness.setPayCount(getLong(posBusiRatesList.get(j),"pbrCredit"));			//出账额度
							//rateMap对象提取
							bdBusiness.setPkFee(getInt(rateMap ,"id"));										//费	率
							//bankInfoMap对象提取					
							bdBusiness.setAccountNo(getString(bankInfoMap,"mbiAccountno"));					//开户账号
							bdBusiness.setAccountName(getString(bankInfoMap,"mbiAccountuser"));				//开户名称
							bdBusiness.setBankNo(getString(bankInfoMap,"mbiBankno"));						//开户行号
							bdBusiness.setBankName(getString(bankInfoMap,"mbiBankname"));					//开户行名
							//branchCompanyMap对象提取
							bdBusiness.setAegisCompany(getString(branchCompanyMap,"bcompany_name"));		//维护方
							
							//判断新增or修改
							Where where=new Where(BdBusiness.class);
							where.addEqual("hmId", bdBusiness.getHmId());
							where.addEqual("htId", bdBusiness.getHtId());
							where.addEqual("omId", bdBusiness.getOmId());
							where.addEqual("otId", bdBusiness.getOtId());
							where.addEqual("client", bdBusiness.getClient());
							where.addEqual("transMode", bdBusiness.getTransMode());
							where.addEqual("cardType", bdBusiness.getCardType());
							where.addEqual("cardMedia", bdBusiness.getCardMedia());
							where.addEqual("businessType", bdBusiness.getBusinessType());
							List<BdBusiness>list=businessService.findList(where);
							if(list.size()>0){
								bdBusiness.setPkBusiness(list.get(0).getPkBusiness());
								//修改入库
								businessService.update(bdBusiness);
							}else{
								//添加入库
								businessService.save(bdBusiness);
							}
						}
				  	}
				}
			}
		}catch(Exception e){
			logger.error("业务信息整理出错"+e);
			e.printStackTrace();
			b=false;
		}		
		return b;
	}
	
	
	/**
	 * 将值转成String
	 * @return
	 */
	public String getString(Map<String, Object> map,String key)
    {
        if (map==null||map.get(key) == null || map.get(key).equals("null")||map.get(key).equals("")){
        	return "";
        }else{
        	return map.get(key)+"";
        }
    }	
	
	/**
	 * 将值转成int
	 * @return
	 */
	public Integer getInt(Map<String, Object> map,String key)
    {
        if (map.get(key) == null || map.get(key).equals("null")||map.get(key).equals("")){
        	return 0;
        }else{
        	return Integer.valueOf(""+map.get(key));
        }
    }	
	
	/**
	 * 将值转成Long
	 * @return
	 */
	public Long getLong(Map<String, Object> map,String key)
    {
        if (map.get(key) == null || map.get(key).equals("null")||map.get(key).equals("")){
        	return 0L;
        }else{
        	return Long.valueOf((""+map.get(key)).replace(".", ""));
        }
    }	
}
